package server

import (
	"context"
	"video/user-server/basic/config"
	__ "video/user-server/basic/proto"
	"video/user-server/mode"
)

type Server struct {
	__.UnsafeVideoServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Greet(_ context.Context, in *__.StreamReq) (*__.StreamResp, error) {

	return &__.StreamResp{}, nil
}
func (s *Server) VideoAdd(_ context.Context, in *__.VideoAddReq) (*__.VideoAddResp, error) {
	video := mode.Video{
		UserId:   in.UserId,
		Title:    in.Title,
		Video:    in.Video,
		Describe: in.Describe,
		Category: in.Category,
		State:    1,
	}
	config.DB.Create(&video)

	return &__.VideoAddResp{
		Id: int64(video.Id),
	}, nil
}
func (s *Server) VideoModify(_ context.Context, in *__.VideoModifyReq) (*__.VideoModifyResp, error) {
	var video mode.Video
	config.DB.Find(&video)
	m := mode.Video{
		Id:    uint64(in.Id),
		State: int32(in.State),
	}
	config.DB.Updates(&m)

	return &__.VideoModifyResp{
		Id: int64(m.Id),
	}, nil
}
func (s *Server) VideoList(_ context.Context, in *__.VideoListReq) (*__.VideoListResp, error) {

	page := in.Upper
	if page <= 0 {
		page = 1
	}

	pageSize := in.Below
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	config.DB.Offset(int(offset)).Limit(int(pageSize))
	var Video []mode.Video
	config.DB.Find(&Video)
	var VideoList []*__.VideoList
	for _, video := range Video {
		list := __.VideoList{
			UserId:   video.UserId,
			Title:    video.Title,
			Video:    video.Video,
			Describe: video.Describe,
			Category: video.Category,
		}
		VideoList = append(VideoList, &list)

	}

	return &__.VideoListResp{
		List: VideoList,
	}, nil
}
